package com.cy.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.cy.condition.BackRoleCondition;
import com.cy.entity.BackRole;
import com.cy.entity.BackUser;
import com.cy.util.StringUtils;

@Component("backRole")
public class BackRoleDao extends BaseDAOHibernate<BackRole>{

	public List<BackRole> listBackRoleByCondition(int firstResult,int maxResults, BackRoleCondition condition) {
		List<BackRole> backRoles=new ArrayList<BackRole>();
		Session session=this.getSession();
		StringBuffer hql=new StringBuffer();
		hql.append(" FROM BackRole b WHERE 1=1 ");
		if(condition!=null){
			if(StringUtils.isNotEmpty(condition.getName())){
				hql.append(" AND b.name like :name");
			}
		}
		hql.append(" ORDER BY b.id ");
		Query query=session.createQuery(hql.toString());
		if(condition!=null){
			if(StringUtils.isNotEmpty(condition.getName())){
				query.setParameter("name", "%"+condition.getName()+"%");
			}
		}
		if(maxResults==0){
			
		}else{
			query.setFirstResult(firstResult);
			query.setMaxResults(maxResults);
		}
		backRoles=query.list();
		return backRoles;
	}
	
	public void deleteRolePurviews(Long roleId){
		Session session=this.getSession();
		StringBuffer hql =new StringBuffer();
		hql.append("DELETE FROM BackRolePurView rp WHERE rp.role.id=:rId");
		Query query=session.createQuery(hql.toString());
		query.setParameter("rId", roleId);
		query.executeUpdate();
	}
	
	public BackRole findDetailBackRoleById(Long id) {
		Session session=this.getSession();
		BackRole backRole=getObject(BackRole.class, id);
		Hibernate.initialize(backRole.getRolePurviewSet());
		return backRole;
	}

	public List<BackUser> findBackUserByRoleId(Long roleId) {
		String hql="SELECT br.backUser FROM BackUserRole br WHERE br.role.id=:roleId";
		return this.getSession().createQuery(hql).setParameter("roleId", roleId).list();
	}

	public List<BackUser> findBackUserNotEqualRoleId(Long roleId) {
		String hql="SELECT bu FROM BackUser bu WHERE NOT EXISTS( SELECT bur FROM BackUserRole bur WHERE bur.role.id=:roleId AND bu.id=bur.backUser.id)";
		return this.getSession().createQuery(hql).setParameter("roleId", roleId).list();
	}
	
}
